package com.docmgmt.mvp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.docmgmt.mvp.dto.AiFeedbackVO;
import com.docmgmt.mvp.dto.SubmitFeedbackRequest;
import com.docmgmt.mvp.entity.ConversationEntity;
import com.docmgmt.mvp.entity.FeedbackEntity;
import com.docmgmt.mvp.exception.BusinessException;
import com.docmgmt.mvp.exception.ForbiddenException;
import com.docmgmt.mvp.mapper.ConversationMapper;
import com.docmgmt.mvp.mapper.FeedbackMapper;
import com.docmgmt.mvp.service.FeedbackService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * AI反馈服务实现（AI-003）
 *
 * @author Dora
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class FeedbackServiceImpl extends ServiceImpl<FeedbackMapper, FeedbackEntity> implements FeedbackService {

    private final FeedbackMapper feedbackMapper;
    private final ConversationMapper conversationMapper;
    private final ObjectMapper objectMapper;

    /**
     * 提交AI答案反馈
     * - 验证conversation是否存在且属于当前用户
     * - 允许修改已有反馈
     * - 更新conversation.feedback字段
     */
    @Transactional
    @Override
    public AiFeedbackVO submitFeedback(SubmitFeedbackRequest request, Long userId) {
        log.info("提交AI反馈：conversationId={}, feedbackType={}, userId={}",
                request.getConversationId(), request.getFeedbackType(), userId);

        // 1. 验证conversation是否存在且属于当前用户
        ConversationEntity conversation = conversationMapper.selectById(request.getConversationId());
        if (conversation == null) {
            throw new BusinessException("对话记录不存在");
        }
        if (!conversation.getUserId().equals(userId)) {
            throw new ForbiddenException("无权对该对话进行反馈");
        }

        // 2. negative反馈必须填写原因
        if ("negative".equals(request.getFeedbackType()) &&
                (request.getReason() == null || request.getReason().trim().isEmpty())) {
            throw new BusinessException("negative反馈必须填写原因");
        }

        // 3. 检查是否已反馈（允许修改反馈）
        LambdaQueryWrapper<FeedbackEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FeedbackEntity::getConversationId, request.getConversationId())
                .eq(FeedbackEntity::getUserId, userId);

        FeedbackEntity existingFeedback = feedbackMapper.selectOne(queryWrapper);

        if (existingFeedback != null) {
            // 更新已有反馈
            log.info("更新已有反馈：feedbackId={}", existingFeedback.getId());

            existingFeedback.setFeedbackType(request.getFeedbackType());
            existingFeedback.setReason(request.getReason());
            existingFeedback.setTags(serializeTags(request.getTags()));

            feedbackMapper.updateById(existingFeedback);

            // 更新conversation的feedback字段
            conversation.setFeedback(request.getFeedbackType());
            conversationMapper.updateById(conversation);

            return convertToVO(existingFeedback);
        }

        // 4. 创建新反馈记录
        FeedbackEntity feedback = new FeedbackEntity();
        feedback.setConversationId(request.getConversationId());
        feedback.setUserId(userId);
        feedback.setFeedbackType(request.getFeedbackType());
        feedback.setReason(request.getReason());
        feedback.setTags(serializeTags(request.getTags()));
        feedback.setCreatedAt(LocalDateTime.now());

        feedbackMapper.insert(feedback);

        // 5. 更新conversation的feedback字段
        conversation.setFeedback(request.getFeedbackType());
        conversationMapper.updateById(conversation);

        log.info("反馈提交成功：feedbackId={}", feedback.getId());

        return convertToVO(feedback);
    }

    /**
     * 将标签列表序列化为JSON字符串
     */
    private String serializeTags(java.util.List<String> tags) {
        if (tags == null || tags.isEmpty()) {
            return null;
        }
        try {
            return objectMapper.writeValueAsString(tags);
        } catch (JsonProcessingException e) {
            log.warn("标签序列化失败：{}", tags, e);
            return null;
        }
    }

    /**
     * 转换为VO对象
     */
    private AiFeedbackVO convertToVO(FeedbackEntity entity) {
        return AiFeedbackVO.builder()
                .id(entity.getId())
                .feedbackType(entity.getFeedbackType())
                .createdAt(entity.getCreatedAt())
                .build();
    }
}
